package com.kwdb.importtool.ui;

import com.kwdb.importtool.config.DatabaseConfig;
import com.kwdb.importtool.config.MigrationConfig;
import com.kwdb.importtool.util.LoggerUtil;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 配置面板
 * 用于配置KWDB和MySQL连接参数以及迁移选项
 */
@Data
public class ConfigPanel extends JPanel {
    private static final Logger logger = LoggerFactory.getLogger(ConfigPanel.class);

    // 主配置对象
    private DatabaseConfig dbConfig;
    private MigrationConfig migrationConfig;

    // 配置文件相关
    private JTextField configFileField;
    private JButton browseConfigButton;
    private JButton loadConfigButton;
    private JButton saveConfigButton;

    // KWDB配置组件
    private JTextField kwdbUrlField;
    private JTextField kwdbUserField;
    private JPasswordField kwdbPasswordField;
    private JButton testKwdbButton;

    // MySQL配置组件（用于验证）
/*    private JTextField mysqlUrlField;
    private JTextField mysqlUserField;
    private JPasswordField mysqlPasswordField;
    private JButton testMysqlButton;*/

    // 迁移选项组件
    private JCheckBox createDatabaseCheck;
    private JCheckBox createTablesCheck;
    private JCheckBox importDataCheck;
    private JCheckBox createIndexesCheck;
    private JCheckBox createSequencesCheck;
    private JCheckBox includeCommentsCheck;

    private JSpinner batchSizeSpinner;
    private JCheckBox skipErrorsCheck;
    private JCheckBox validateDataCheck;
    private JCheckBox parallelMigrationCheck;
    private JSpinner maxThreadsSpinner;

    // 高级选项组件
    private JCheckBox verboseLoggingCheck;
    private JCheckBox backupOriginalCheck;
    private JTextField outputDirField;
    private JButton browseOutputButton;

    // 测试连接结果标签
    private JLabel kwdbTestResult;
    private JLabel mysqlTestResult;

    public ConfigPanel() {
        this.dbConfig = new DatabaseConfig();
        this.migrationConfig = new MigrationConfig();
        initializeUI();
        loadDefaultConfig();
    }

    public ConfigPanel(DatabaseConfig dbConfig, MigrationConfig migrationConfig) {
        this.dbConfig = dbConfig;
        this.migrationConfig = migrationConfig;
        initializeUI();
        updateUIFromConfig();
    }

    /**
     * 初始化用户界面
     */
    private void initializeUI() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("配置文件", createConfigFilePanel());
        tabbedPane.addTab("数据库连接", createDatabaseConfigPanel());
        tabbedPane.addTab("迁移选项", createMigrationPanel());
        tabbedPane.addTab("高级选项", createAdvancedPanel());

        add(tabbedPane, BorderLayout.CENTER);

        // 添加底部按钮面板
        add(createButtonPanel(), BorderLayout.SOUTH);
    }

    /**
     * 创建配置文件面板
     */
    private JPanel createConfigFilePanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createTitledBorder("配置文件管理"));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        // 配置文件路径
        gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0;
        panel.add(new JLabel("配置文件路径:"), gbc);

        gbc.gridx = 1; gbc.weightx = 1;
        configFileField = new JTextField(30);
        configFileField.setToolTipText("选择或输入配置文件路径");
        panel.add(configFileField, gbc);

        gbc.gridx = 2; gbc.weightx = 0;
        browseConfigButton = new JButton("浏览...");
        browseConfigButton.addActionListener(new BrowseConfigAction());
        panel.add(browseConfigButton, gbc);

        // 按钮行
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
/*        loadConfigButton = new JButton("加载配置");
        loadConfigButton.addActionListener(new LoadConfigAction());
        buttonPanel.add(loadConfigButton);*/

        saveConfigButton = new JButton("保存配置");
        saveConfigButton.addActionListener(new SaveConfigAction());
        buttonPanel.add(saveConfigButton);

        gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 3;
        panel.add(buttonPanel, gbc);

        // 说明文本
        gbc.gridy = 2; gbc.gridwidth = 3;
        JTextArea helpText = new JTextArea(3, 40);
        helpText.setText("提示：可以保存当前配置到文件，方便下次使用。\n" +
                "配置文件格式支持：JSON、Properties、HOCON");
        helpText.setEditable(false);
        helpText.setBackground(panel.getBackground());
        helpText.setLineWrap(true);
        helpText.setWrapStyleWord(true);
        panel.add(helpText, gbc);

        return panel;
    }

    /**
     * 创建数据库配置面板
     */
    private JPanel createDatabaseConfigPanel() {
        JPanel panel = new JPanel(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        // KWDB配置区域
        JPanel kwdbPanel = createDatabaseSubPanel("KWDB 配置", true);
        panel.add(kwdbPanel, createGbc(0, 0, 2, 1));

        // MySQL配置区域
/*        JPanel mysqlPanel = createDatabaseSubPanel("MySQL 配置（可选，用于验证）", false);
        panel.add(mysqlPanel, createGbc(0, 1, 2, 1));*/

        return panel;
    }

    /**
     * 创建数据库子面板
     */
    private JPanel createDatabaseSubPanel(String title, boolean isKwdb) {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createTitledBorder(title));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(3, 5, 3, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        int row = 0;

        // URL
        gbc.gridx = 0; gbc.gridy = row; gbc.weightx = 0;
        panel.add(new JLabel("连接URL:"), gbc);

        gbc.gridx = 1; gbc.weightx = 1;
        JTextField urlField = new JTextField(25);
        urlField.setToolTipText("示例: jdbc:kaiwudb://localhost:8123/default 或 jdbc:mysql://localhost:3306/dbname");
        panel.add(urlField, gbc);

        // 用户名
        gbc.gridx = 0; gbc.gridy = ++row; gbc.weightx = 0;
        panel.add(new JLabel("用户名:"), gbc);

        gbc.gridx = 1; gbc.weightx = 1;
        JTextField userField = new JTextField(20);
        panel.add(userField, gbc);

        // 密码
        gbc.gridx = 0; gbc.gridy = ++row; gbc.weightx = 0;
        panel.add(new JLabel("密码:"), gbc);

        gbc.gridx = 1; gbc.weightx = 1;
        JPasswordField passwordField = new JPasswordField(20);
        panel.add(passwordField, gbc);

        // 测试按钮和结果
        gbc.gridx = 0; gbc.gridy = ++row; gbc.gridwidth = 2;
        JPanel testPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton testButton = new JButton("测试连接");
        JLabel testResult = new JLabel("未测试");
        testResult.setForeground(Color.GRAY);

        testPanel.add(testButton);
        testPanel.add(testResult);
        panel.add(testPanel, gbc);

        // 根据数据库类型设置组件引用和事件
        if (isKwdb) {
            kwdbUrlField = urlField;
            kwdbUserField = userField;
            kwdbPasswordField = passwordField;
            testKwdbButton = testButton;
            kwdbTestResult = testResult;
            testButton.addActionListener(new TestKwdbAction());
        }/* else {
            mysqlUrlField = urlField;
            mysqlUserField = userField;
            mysqlPasswordField = passwordField;
            testMysqlButton = testButton;
            mysqlTestResult = testResult;
            testButton.addActionListener(new TestMysqlAction());
        }*/

        return panel;
    }

    /**
     * 创建迁移选项面板
     */
    private JPanel createMigrationPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createTitledBorder("迁移选项"));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        int row = 0;

        // 迁移操作选项
        gbc.gridx = 0; gbc.gridy = row; gbc.gridwidth = 2;
        JLabel operationsLabel = new JLabel("选择要执行的迁移操作:");
        operationsLabel.setFont(operationsLabel.getFont().deriveFont(Font.BOLD));
        panel.add(operationsLabel, gbc);

        // 第一列选项
        gbc.gridx = 0; gbc.gridy = ++row; gbc.gridwidth = 1;
        createDatabaseCheck = createCheckBox("创建数据库", true);
        panel.add(createDatabaseCheck, gbc);

        gbc.gridx = 0; gbc.gridy = ++row;
        createTablesCheck = createCheckBox("创建表结构", true);
        panel.add(createTablesCheck, gbc);

        gbc.gridx = 0; gbc.gridy = ++row;
        importDataCheck = createCheckBox("导入数据", true);
        panel.add(importDataCheck, gbc);

        // 第二列选项
        gbc.gridx = 1; gbc.gridy = 1;
        createIndexesCheck = createCheckBox("创建索引", true);
        panel.add(createIndexesCheck, gbc);

        gbc.gridx = 1; gbc.gridy = 2;
        createSequencesCheck = createCheckBox("创建序列", true);
        panel.add(createSequencesCheck, gbc);

        gbc.gridx = 1; gbc.gridy = 3;
        includeCommentsCheck = createCheckBox("包含注释", true);
        panel.add(includeCommentsCheck, gbc);

        // 性能选项
        gbc.gridx = 0; gbc.gridy = 4; gbc.gridwidth = 2;
        panel.add(createSeparator("性能选项"), gbc);

        gbc.gridx = 0; gbc.gridy = 5; gbc.gridwidth = 1;
        panel.add(new JLabel("批处理大小:"), gbc);

        gbc.gridx = 1; gbc.gridy = 5;
        batchSizeSpinner = new JSpinner(new SpinnerNumberModel(1000, 1, 100000, 100));
        batchSizeSpinner.setToolTipText("每次批量处理的记录数");
        panel.add(batchSizeSpinner, gbc);

        gbc.gridx = 0; gbc.gridy = 6;
        parallelMigrationCheck = createCheckBox("并行迁移", false);
        parallelMigrationCheck.setToolTipText("启用多线程并行处理");
        panel.add(parallelMigrationCheck, gbc);

        gbc.gridx = 1; gbc.gridy = 6;
        panel.add(new JLabel("最大线程数:"), gbc);

        gbc.gridx = 2; gbc.gridy = 6;
        maxThreadsSpinner = new JSpinner(new SpinnerNumberModel(4, 1, 16, 1));
        maxThreadsSpinner.setEnabled(false);
        panel.add(maxThreadsSpinner, gbc);

        // 启用/禁用线程数控制
        parallelMigrationCheck.addActionListener(e -> {
            maxThreadsSpinner.setEnabled(parallelMigrationCheck.isSelected());
        });

        // 错误处理选项
        gbc.gridx = 0; gbc.gridy = 7; gbc.gridwidth = 2;
        panel.add(createSeparator("错误处理"), gbc);

        gbc.gridx = 0; gbc.gridy = 8; gbc.gridwidth = 2;
        skipErrorsCheck = createCheckBox("跳过错误继续执行", false);
        skipErrorsCheck.setToolTipText("遇到错误时跳过并继续执行后续语句");
        panel.add(skipErrorsCheck, gbc);

        gbc.gridx = 0; gbc.gridy = 9; gbc.gridwidth = 2;
/*        validateDataCheck = createCheckBox("迁移后验证数据", true);
        validateDataCheck.setToolTipText("迁移完成后验证数据的完整性和一致性");*/
//        panel.add(validateDataCheck, gbc);

        return panel;
    }

    /**
     * 创建高级选项面板
     */
    private JPanel createAdvancedPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createTitledBorder("高级选项"));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        int row = 0;

        // 日志选项
/*        gbc.gridx = 0; gbc.gridy = row; gbc.gridwidth = 2;
        panel.add(createSeparator("日志设置"), gbc);*/

/*        gbc.gridx = 0; gbc.gridy = ++row; gbc.gridwidth = 2;
        verboseLoggingCheck = createCheckBox("详细日志记录", false);
        verboseLoggingCheck.setToolTipText("记录更详细的调试信息");
        panel.add(verboseLoggingCheck, gbc);*/

        // 文件选项
        gbc.gridx = 0; gbc.gridy = ++row; gbc.gridwidth = 2;
        panel.add(createSeparator("文件设置"), gbc);

        gbc.gridx = 0; gbc.gridy = ++row; gbc.gridwidth = 1;
        backupOriginalCheck = createCheckBox("备份原文件", true);
        panel.add(backupOriginalCheck, gbc);

//        gbc.gridx = 0; gbc.gridy = ++row;
//        panel.add(new JLabel("输出目录:"), gbc);

/*        gbc.gridx = 1; gbc.gridy = row; gbc.weightx = 1;
        outputDirField = new JTextField(25);
        outputDirField.setToolTipText("迁移过程中生成文件的输出目录");
        panel.add(outputDirField, gbc);*/

/*        gbc.gridx = 2; gbc.gridy = row; gbc.weightx = 0;
        browseOutputButton = new JButton("浏览...");
        browseOutputButton.addActionListener(new BrowseOutputAction());
        panel.add(browseOutputButton, gbc);*/

        // 填充剩余空间
        gbc.gridx = 0; gbc.gridy = ++row; gbc.gridwidth = 3; gbc.weighty = 1;
        panel.add(Box.createVerticalGlue(), gbc);

        return panel;
    }

    /**
     * 创建按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        JButton applyButton = new JButton("应用配置");
        applyButton.addActionListener(new ApplyConfigAction());

        JButton resetButton = new JButton("重置配置");
        resetButton.addActionListener(new ResetConfigAction());

        panel.add(resetButton);
        panel.add(applyButton);

        return panel;
    }

    /**
     * 创建带标题的分隔符
     */
    private JComponent createSeparator(String title) {
        JLabel label = new JLabel(title);
        label.setFont(label.getFont().deriveFont(Font.BOLD));
        return label;
    }

    /**
     * 创建复选框
     */
    private JCheckBox createCheckBox(String text, boolean selected) {
        JCheckBox checkBox = new JCheckBox(text, selected);
        checkBox.setVerticalTextPosition(SwingConstants.TOP);
        return checkBox;
    }

    /**
     * 创建GridBagConstraints辅助方法
     */
    private GridBagConstraints createGbc(int x, int y, int width, int height) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = height;
        gbc.insets = new Insets(2, 2, 2, 2);
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        if (width == 1 && height == 1) {
            gbc.weightx = 1.0;
        }
        return gbc;
    }

    /**
     * 从配置对象更新UI
     */
    public void updateUIFromConfig() {
        // KWDB配置
        kwdbUrlField.setText(dbConfig.getKwdbUrl());
        kwdbUserField.setText(dbConfig.getKwdbUsername());
        kwdbPasswordField.setText(dbConfig.getKwdbPassword());

        // MySQL配置
/*        mysqlUrlField.setText(dbConfig.getMysqlUrl());
        mysqlUserField.setText(dbConfig.getMysqlUsername());
        mysqlPasswordField.setText(dbConfig.getMysqlPassword());*/

        // 迁移选项
        createDatabaseCheck.setSelected(migrationConfig.isCreateDatabase());
        createTablesCheck.setSelected(migrationConfig.isCreateTables());
        importDataCheck.setSelected(migrationConfig.isImportData());
        createIndexesCheck.setSelected(migrationConfig.isCreateIndexes());
        createSequencesCheck.setSelected(migrationConfig.isCreateSequences());
        includeCommentsCheck.setSelected(migrationConfig.isIncludeComments());

        batchSizeSpinner.setValue(migrationConfig.getBatchSize());
        skipErrorsCheck.setSelected(migrationConfig.isSkipErrors());
        //暂定
//        validateDataCheck.setSelected(migrationConfig.isValidateDataCount());
        parallelMigrationCheck.setSelected(migrationConfig.isParallelMigration());
        maxThreadsSpinner.setValue(migrationConfig.getMaxThreads());
        maxThreadsSpinner.setEnabled(migrationConfig.isParallelMigration());

        // 高级选项
//        verboseLoggingCheck.setSelected(migrationConfig.isVerboseLogging());
        backupOriginalCheck.setSelected(migrationConfig.isBackupOriginal());
//        outputDirField.setText(migrationConfig.getOutputDir());
    }

    /**
     * 从UI更新配置对象
     */
    public void updateConfigFromUI() {
        // KWDB配置
        dbConfig.setKwdbUrl(kwdbUrlField.getText().trim());
        dbConfig.setKwdbUsername(kwdbUserField.getText().trim());
        dbConfig.setKwdbPassword(new String(kwdbPasswordField.getPassword()));

        // MySQL配置
/*        dbConfig.setMysqlUrl(mysqlUrlField.getText().trim());
        dbConfig.setMysqlUsername(mysqlUserField.getText().trim());
        dbConfig.setMysqlPassword(new String(mysqlPasswordField.getPassword()));*/

        // 迁移选项
        migrationConfig.setCreateDatabase(createDatabaseCheck.isSelected());
        migrationConfig.setCreateTables(createTablesCheck.isSelected());
        migrationConfig.setImportData(importDataCheck.isSelected());
        migrationConfig.setCreateIndexes(createIndexesCheck.isSelected());
        migrationConfig.setCreateSequences(createSequencesCheck.isSelected());
        migrationConfig.setIncludeComments(includeCommentsCheck.isSelected());

        migrationConfig.setBatchSize((Integer) batchSizeSpinner.getValue());
        migrationConfig.setSkipErrors(skipErrorsCheck.isSelected());
        //暂定
//        migrationConfig.setValidateDataCount(validateDataCheck.isSelected());
        migrationConfig.setParallelMigration(parallelMigrationCheck.isSelected());
        migrationConfig.setMaxThreads((Integer) maxThreadsSpinner.getValue());

        // 高级选项
//        migrationConfig.setVerboseLogging(verboseLoggingCheck.isSelected());
        migrationConfig.setBackupOriginal(backupOriginalCheck.isSelected());
//        migrationConfig.setOutputDir(outputDirField.getText().trim());
    }

    /**
     * 加载默认配置
     */
    private void loadDefaultConfig() {
        updateUIFromConfig();
    }

    /**
     * 验证配置有效性
     */
    public boolean validateConfig() {
        // 检查KWDB配置
        if (kwdbUrlField.getText().trim().isEmpty()) {
            showError("KWDB连接URL不能为空");
            return false;
        }

        if (kwdbUserField.getText().trim().isEmpty()) {
            showError("KWDB用户名不能为空");
            return false;
        }

        // 检查迁移选项
        if (!createDatabaseCheck.isSelected() && !createTablesCheck.isSelected() &&
                !importDataCheck.isSelected() && !createIndexesCheck.isSelected() &&
                !createSequencesCheck.isSelected()) {
            showError("请至少选择一项迁移操作");
            return false;
        }

        return true;
    }

    /**
     * 显示错误消息
     */
    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "配置错误", JOptionPane.ERROR_MESSAGE);
    }

    /**
     * 显示成功消息
     */
    private void showSuccess(String message) {
        JOptionPane.showMessageDialog(this, message, "成功", JOptionPane.INFORMATION_MESSAGE);
    }

    // 内部动作类

    /**
     * 浏览配置文件动作
     */
    private class BrowseConfigAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setDialogTitle("选择配置文件");
            chooser.setAcceptAllFileFilterUsed(true);

            int result = chooser.showOpenDialog(ConfigPanel.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                configFileField.setText(chooser.getSelectedFile().getAbsolutePath());
            }
        }
    }

    /**
     * 加载配置动作
     */
    private class LoadConfigAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String configFile = configFileField.getText().trim();
            if (configFile.isEmpty()) {
                showError("请先选择配置文件");
                return;
            }

            try {
                // 这里应该实现配置加载逻辑
                showSuccess("配置加载成功");
            } catch (Exception ex) {
                logger.error("加载配置失败", ex);
                showError("加载配置失败: " + ex.getMessage());
            }
        }
    }

    /**
     * 保存配置动作
     */
    private class SaveConfigAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("保存配置文件");
            chooser.setSelectedFile(new File("migration-config.json"));

            int result = chooser.showSaveDialog(ConfigPanel.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                try {
                    // 这里应该实现配置保存逻辑
                    showSuccess("配置保存成功");
                } catch (Exception ex) {
                    logger.error("保存配置失败", ex);
                    showError("保存配置失败: " + ex.getMessage());
                }
            }
        }
    }

    /**
     * 测试KWDB连接动作
     */
    private class TestKwdbAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            testKwdbButton.setEnabled(false);
            kwdbTestResult.setText("测试中...");
            kwdbTestResult.setForeground(Color.BLUE);

            //数据库连接测试
            new Thread(() -> {
                Connection conn = null;
                try {
                    // 1. 获取连接参数
                    String url = kwdbUrlField.getText().trim(); // 数据库URL输入框
                    String username = kwdbUserField.getText().trim(); // 用户名输入框
                    String password = new String(kwdbPasswordField.getPassword()); // 密码输入框（JPasswordField）
                    String jarPath = configFileField.getText().trim();
                    // 2. 动态加载JAR包到类加载器
                    addJarToClasspath(jarPath);

                    // 3. 加载KWDB驱动类
                    String driverClassName = "com.kaiwudb.Driver";
                    Class.forName(driverClassName);

                    // 4. 尝试建立连接
                    conn = DriverManager.getConnection(url + "?"+"user="+username+"&password="+password);
                    Statement statement = conn.createStatement();

                    String tableCatalog = "";
                    int lastSlashIndex = url.lastIndexOf('/');
                    if (lastSlashIndex != -1) {
                        String afterSlash = url.substring(lastSlashIndex + 1);

                        int questionMarkIndex = afterSlash.indexOf('?');
                        if (questionMarkIndex != -1) {
                            tableCatalog = afterSlash.substring(0, questionMarkIndex);
                        } else {
                            tableCatalog = afterSlash;
                        }
                    }

                    boolean execute = statement.execute("SELECT 1 FROM information_schema.tables WHERE table_catalog = '"
                            + tableCatalog +
                            "' LIMIT 1;");
                    // 4. 连接成功（更新UI）
                    SwingUtilities.invokeLater(() -> {
                        kwdbTestResult.setText("连接成功");
                        kwdbTestResult.setForeground(Color.GREEN);
                        testKwdbButton.setEnabled(true);
                    });
                } catch (ClassNotFoundException ex) {
                    // 驱动类未找到
                    SwingUtilities.invokeLater(() -> {
                        kwdbTestResult.setText("连接失败：未找到KWDB驱动");
                        kwdbTestResult.setForeground(Color.RED);
                        testKwdbButton.setEnabled(true);
                    });
                } catch (SQLException ex) {
                    // 连接异常（URL/账号/密码错误、数据库未启动等）
                    SwingUtilities.invokeLater(() -> {
                        kwdbTestResult.setText("连接失败：" + ex.getMessage()); // 显示具体错误信息
                        kwdbTestResult.setForeground(Color.RED);
                        testKwdbButton.setEnabled(true);
                    });
                } catch (Exception ex) {
                    // 其他未知异常
                    SwingUtilities.invokeLater(() -> {
                        kwdbTestResult.setText("连接失败：" + ex.getMessage());
                        kwdbTestResult.setForeground(Color.RED);
                        testKwdbButton.setEnabled(true);
                    });
                } finally {
                    // 5. 关闭连接（释放资源）
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (SQLException ex) {
                            // 关闭连接失败不影响结果，仅打印日志
                            ex.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    /**
     * 动态将JAR包添加到当前类加载器的类路径中
     * @param jarPath JAR文件的绝对路径
     * @throws Exception 加载失败时抛出异常
     */
    private void addJarToClasspath(String jarPath) throws Exception {
        File jarFile = new File(jarPath);
        if (!jarFile.exists() || !jarPath.endsWith(".jar")) {
            throw new IllegalArgumentException("JAR文件不存在或路径无效：" + jarPath);
        }

        // 获取系统类加载器（URLClassLoader）
        URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        addUrlMethod.setAccessible(true); // 允许访问私有方法
        addUrlMethod.invoke(classLoader, jarFile.toURI().toURL()); // 将JAR路径添加到类加载器
    }

    /**
     * 测试MySQL连接动作
     */
/*    private class TestMysqlAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
        }
    }*/

    /**
     * 浏览输出目录动作
     */
    private class BrowseOutputAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setDialogTitle("选择输出目录");

            int result = chooser.showOpenDialog(ConfigPanel.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                String selectedPath = chooser.getSelectedFile().getAbsolutePath();
                outputDirField.setText(selectedPath);

                // 初始化日志系统，使用最新的输出目录配置
                initializeLoggingWithNewOutputDir(selectedPath);
            }
        }
    }

    /**
     * 使用新的输出目录初始化日志系统
     */
    private void initializeLoggingWithNewOutputDir(String outputDir) {
        try {
            // 更新配置对象
            updateConfigFromUI();

            // 构建配置参数
            String configFile = configFileField.getText().trim();
            if (configFile.isEmpty()) {
                configFile = null;
            }

            // 使用LoggerUtil重新初始化日志系统
            LoggerUtil.initializeLogging(configFile, outputDir);

            // 记录日志系统重新初始化的信息
            logger.info("日志系统已重新初始化");
            logger.info("输出目录: {}", outputDir);

            // 可选：显示成功消息
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(ConfigPanel.this,
                        String.format("日志配置已更新:\n输出目录: %s",
                                outputDir),
                        "配置更新",
                        JOptionPane.INFORMATION_MESSAGE);
            });

        } catch (Exception ex) {
            logger.error("重新初始化日志系统失败", ex);
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(ConfigPanel.this,
                        "日志系统重新初始化失败: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            });
        }
    }

    /**
     * 应用配置动作
     */
    private class ApplyConfigAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!validateConfig()) {
                return;
            }

            updateConfigFromUI();
            showSuccess("配置已应用");
        }
    }

    /**
     * 重置配置动作
     */
    private class ResetConfigAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(ConfigPanel.this,
                    "确定要重置所有配置吗？", "确认重置", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.YES_OPTION) {
                dbConfig = new DatabaseConfig();
                migrationConfig = new MigrationConfig();
                updateUIFromConfig();
                showSuccess("配置已重置");
            }
        }
    }

    // 公共方法

    public DatabaseConfig getDatabaseConfig() {
        updateConfigFromUI();
        return dbConfig;
    }

    public MigrationConfig getMigrationConfig() {
        updateConfigFromUI();
        return migrationConfig;
    }

    public boolean isConfigValid() {
        return validateConfig();
    }
}